package com.qfdu.repo.common;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static final String MYBATIS_FILE = "mybatis-config.xml";
    private static InputStream inputStream;
    private static SqlSessionFactoryBuilder builder;
    private static SqlSessionFactory factory;

    private static SqlSession sqlSession;

    /**
     * ① 读取mybatis核心配置文件:mybatis-config.xml文件
     * ② 解析该文件
     * ③ 创建一个mybatis的sqlSession对象
     * ④ 供以后进行使用
     * ⑤ 通过sqlSession获取特定的Mapper(Dao对象)
     * ⑥ 调用dao对应的方法
     * ⑦ 提交事务，关闭等
     */

    static {
        //加载核心配置文件
        try {
            //通过io输入流，读取核心配置文件
            inputStream = Resources.getResourceAsStream(MYBATIS_FILE);
            builder = new SqlSessionFactoryBuilder();
            factory = builder.build(inputStream);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过泛型获取Mapper对象的方法
     *
     * @param clz 自定义的类型
     * @param <T> 获取到的类型对象
     * @return
     */
    public static <T> T getMapper(Class<T> clz) {
        sqlSession = factory.openSession();
        return sqlSession.getMapper(clz);
    }

    /**
     * 提交事务
     */
    public static void commit() {
        sqlSession.commit();
    }

    public static void close(){
        try {
            sqlSession.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
